<template>
	<view class="container">
		<!-- 缺少行驶证副本提醒 -->
		<view v-if="!hasLicenseBack" class="missing-license-notice">
			<view class="notice-content">
				<uni-icons type="info" size="20" color="#ff6b35"></uni-icons>
				<text class="notice-text">请先补充行驶证副本才能使用页面其他功能</text>
			</view>
			<button class="upload-license-btn" @click="uploadLicenseBack">上传副本</button>
		</view>

		
		<uni-section class="section"
			title="车辆基础信息" 
			type="line">
			<template v-slot:decoration>
				<uni-icon name="car" size="16" color="#409eff"></uni-icon>
			</template>
			<template v-slot:right>
				<view class="tag-group">
					<!-- 保养信息待完善 -->
					<uni-tag 
						v-if="isMaintenanceIncomplete"
						text="待完善" 
						type="error"
						size="small">
					</uni-tag>
					<!-- 未绑定状态 -->
					<uni-tag 
						v-if="isUnbound"
						text="未绑定" 
						type="error"
						size="small">
					</uni-tag>
					<!-- 待服务状态 -->
					<uni-tag 
						v-if="hasServicePending"
						text="待服务" 
						type="warning"
						size="small">
					</uni-tag>
				</view>
			</template>
			<view class="info-card">
			
			<uni-row :gutter="16">
				<uni-col :span="12">
					<view class="info-item">
						<text class="label">车牌号码</text>
						<text class="value">{{ formData.plate_number || '--' }}</text>
					</view>
				</uni-col>
				<uni-col :span="12">
					<view class="info-item">
						<text class="label">车辆类型</text>
						<text class="value">{{ formData.license_info?.vehicle_type || '--' }}</text>
					</view>
				</uni-col>
			</uni-row>
			<uni-row :gutter="16">
				<uni-col :span="12">
					<view class="info-item">
						<text class="label">车主信息</text>
						<text class="value">{{ maskOwnerName(formData.license_info?.owner) }}</text>
					</view>
				</uni-col>
				<uni-col :span="12">
					<view class="info-item">
						<text class="label">使用性质</text>
						<text class="value">{{ formData.license_info?.use_nature || '--' }}</text>
					</view>
				</uni-col>
			</uni-row>
			<uni-row :gutter="16">
				<uni-col :span="12">
					<view class="info-item">
						<text class="label">注册日期</text>
						<uni-dateformat class="value" :format="dateformat1" :date="formData.license_info?.register_date"></uni-dateformat>
					</view>
				</uni-col>
				<uni-col :span="12">
					<view class="info-item">
						<text class="label">发证日期</text>
						<uni-dateformat class="value" :format="dateformat1" :date="formData.license_info?.issue_date"></uni-dateformat>
					</view>
				</uni-col>
			</uni-row>
		</view>
		</uni-section>
			
		

		<!-- 保险信息 -->
		<uni-section
			title="保险信息" 
			type="line"
			:class="{ 'urgent-section': isInsuranceServiceTime }">
			<template v-slot:decoration>
				<uni-icon name="shield" size="16" :color="getStatusColor(getInsuranceStatusType())"></uni-icon>
			</template>
			<template v-slot:right>
				<view class="header-button-group">
					<button v-if="!isInsuranceServiceTime" class="header-btn primary" @click="editInsurance">手工录入</button>
					<button v-if="isInsuranceServiceTime" class="header-btn urgent" @click="completeInsuranceService">已服务</button>
				</view>
			</template>
			<view class="info-card" :class="{ 'urgent-card': isInsuranceServiceTime }">
				<view class="info-item">
					<text class="label">保险生效日期</text>
					<view class="value">
						<uni-datetime-picker 
							ref="insuranceDatePicker"
							v-model="formData.insurance_info.effective_date"
							type="date"
							return-type="string"
							:start="oneYearAgoDate"
							:end="todayDate"
							placeholder="请选择保险生效日期"
							:border="true"
							:clear-icon="false">
						</uni-datetime-picker>
					</view>
				</view>
				<view class="info-item">
					<text class="label">保险可办期</text>
					<text class="value">{{ getInsuranceTodoRange() }}</text>
				</view>
			</view>
		</uni-section>
		<!-- 保养信息 -->
		<uni-section 
			title="保养信息" 
			type="line"
			:class="{ 'urgent-section': isMaintenanceServiceTime }">
			<template v-slot:decoration>
				<uni-icon name="setting" size="16" :color="getStatusColor(getMaintenanceStatusType())"></uni-icon>
			</template>
			<template v-slot:right>
				<view v-if="showMaintenanceRegister" class="header-button-group">
					<button class="header-btn primary" @click="registerMaintenance">登记保养信息</button>
				</view>
				<view v-else-if="isMaintenanceServiceTime" class="header-button-group">
					<button class="header-btn primary" @click="completeMaintenanceService">已服务</button>
				</view>
			</template>
			<view class="info-card" :class="{ 'urgent-card': isMaintenanceServiceTime }">
				<view class="info-item">
					<text class="label">上次保养日期</text>
					<view class="value">
						<uni-datetime-picker 
							ref="maintenanceDatePicker"
							v-model="formData.maintenance_info.last_maintenance_date"
							type="date"
							return-type="string"
							:end="todayDate"
							placeholder="请选择保养日期"
							:border="true"
							:clear-icon="false">
						</uni-datetime-picker>
					</view>
				</view>
				<view class="info-item">
					<text class="label">总里程数</text>
					<view class="value">
						<uni-easyinput
							v-model="formData.maintenance_info.mileage"
							type="number"
							placeholder="请输入总里程数(km)"
							:border="true">
						</uni-easyinput>
						
					</view>
				</view>
				<view class="info-item">
					<text class="label">机油里程数</text>
					<view class="value">
						<uni-data-checkbox 
							v-model="formData.maintenance_info.oil_mileage" 
							:localdata="oilMileageOptions"
							mode="button"
							selectedColor="#007AFF">
						</uni-data-checkbox>
					</view>
				</view>
				<view class="info-item">
					<text class="label">保养可办期</text>
					<text class="value">{{ getMaintenanceTodoRange() }}</text>
				</view>
			</view>
		</uni-section>

		<!-- 车检信息 -->
		<uni-section 
			title="车检信息" 
			type="line"
			:class="{ 'urgent-section': isInspectionServiceTime }">
			<template v-slot:decoration>
				<uni-icon name="checkmark-circle" size="16" :color="getStatusColor(getInspectionStatusType())"></uni-icon>
			</template>
			<template v-slot:right>
				<view class="header-button-group">
					<button class="header-btn primary" @click="editInspection">手工录入</button>
					<button v-if="isInspectionServiceTime" class="header-btn secondary" @click="completeInspectionService">已服务</button>
				</view>
			</template>
			<view class="info-card" :class="{ 'urgent-card': isInspectionServiceTime }">
				<view class="info-item">
					<text class="label">上次车检日期</text>
					<uni-dateformat class="value" :format="dateformat1" :date="formData.inspection_info?.last_inspection_date"></uni-dateformat>
				</view>
				<view class="info-item">
					<text class="label">下次车检日期</text>
					<view class="value">
						<uni-datetime-picker 
							ref="inspectionDatePicker"
							v-model="formData.inspection_info.next_inspection_date"
							type="date"
							return-type="string"
							:start="todayDate"
							:end="getFutureDate"
							placeholder="请选择下次车检日期"
							:border="true"
							:clear-icon="false">
						</uni-datetime-picker>
					</view>
				</view>
				<view class="info-item">
					<text class="label">车检可办期</text>
					<text class="value">{{ getInspectionTodoRange() }}</text>
				</view>
			</view>
		</uni-section>
<!-- 操作按钮区 -->

	<view class="operation-buttons">
		<button 
			class="operation-btn bind-update-btn single-btn" 
			type="primary"
			@click="bindUpdate"
			:disabled="!canBindUpdate">
			绑定更新
		</button>
	</view>
		<!-- 车辆标记信息 -->
		<uni-section 
			title="车辆标记" 
			type="line"
			v-if="hasLicenseBack">
			<template v-slot:decoration>
				<uni-icon name="flag" size="16" color="#ff9900"></uni-icon>
			</template>
			<view class="info-card">
				<uni-row :gutter="16">
					<uni-col :span="12">
						<view class="mark-item">
							<text class="mark-label">事故车</text>
							<uni-tag 
								:text="formData.is_accident_vehicle ? '是' : '否'" 
								:type="formData.is_accident_vehicle ? 'error' : 'default'"
								size="mini">
							</uni-tag>
							<button 
								class="mark-edit-btn" 
								@click="toggleAccidentVehicle"
								:disabled="!hasLicenseBack">
								{{ formData.is_accident_vehicle ? '取消标记' : '标记为事故车' }}
							</button>
						</view>
					</uni-col>
					<uni-col :span="12">
						<view class="mark-item">
							<text class="mark-label">改装车</text>
							<uni-tag 
								:text="formData.is_modified_vehicle ? '是' : '否'" 
								:type="formData.is_modified_vehicle ? 'error' : 'default'"
								size="mini">
							</uni-tag>
							<button 
								class="mark-edit-btn" 
								@click="toggleModifiedVehicle"
								:disabled="!hasLicenseBack">
								{{ formData.is_modified_vehicle ? '取消标记' : '标记为改装车' }}
							</button>
						</view>
					</uni-col>
				</uni-row>
			</view>
		</uni-section>

		<!-- 证件照片 -->
		<uni-section 
			title="证件照片" 
			type="line">
			<template v-slot:decoration>
				<uni-icon name="photo" size="16" color="#909399"></uni-icon>
			</template>
			<view class="photo-card">
				<uni-row :gutter="16">
					<uni-col :span="6">
						<view class="photo-item" @click="previewImage(formData.license_photos?.car_license_face?.url)">
							<image v-if="formData.license_photos?.car_license_face?.url" :src="formData.license_photos.car_license_face.url" mode="aspectFit" class="photo-image"></image>
							<view v-else class="photo-placeholder">
								<uni-icon name="photo" size="40" color="#ddd"></uni-icon>
								<text class="placeholder-text">行驶证正本</text>
							</view>
							<text class="photo-label">行驶证正本</text>
						</view>
					</uni-col>
					<uni-col :span="6">
						<view class="photo-item" @click="previewImage(formData.license_photos?.car_license_back?.url)">
							<image v-if="formData.license_photos?.car_license_back?.url" :src="formData.license_photos.car_license_back.url" mode="aspectFit" class="photo-image"></image>
							<view v-else class="photo-placeholder">
								<uni-icon name="photo" size="40" color="#ddd"></uni-icon>
								<text class="placeholder-text">行驶证副本</text>
							</view>
							<text class="photo-label">行驶证副本</text>
						</view>
					</uni-col>
				</uni-row>
			</view>
		</uni-section>

		



		<!-- 保养信息登记弹窗 -->
		<uni-popup ref="maintenancePopup" type="center" :mask-click="false">
			<view class="maintenance-popup">
				<view class="popup-title">登记保养信息</view>
				<uni-forms ref="maintenanceForm" :model="maintenanceForm" :rules="maintenanceRules">
					<uni-forms-item label="上次保养日期" name="lastDate" required>
						<uni-datetime-picker
							v-model="maintenanceForm.lastDate"
							type="date"
							return-type="string"
							:end="todayDate"
							placeholder="请选择保养日期"
							:clear-icon="false">
						</uni-datetime-picker>
					</uni-forms-item>
					<uni-forms-item label="总公里数(km)" name="totalMileage" required>
						<uni-easyinput
							v-model="maintenanceForm.totalMileage"
							type="number"
							placeholder="请输入总公里数">
						</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="机油公里数(km)" name="oilMileage" required>
						<uni-data-checkbox 
							v-model="maintenanceForm.oilMileage" 
							:localdata="oilMileageOptions"
							mode="button"
							selectedColor="#007AFF">
						</uni-data-checkbox>
					</uni-forms-item>
				</uni-forms>
				<view class="popup-actions">
					<button class="cancel-btn" @click="closeMaintenancePopup">取消</button>
					<button class="confirm-btn" @click="saveMaintenanceInfo">确认</button>
				</view>
			</view>
		</uni-popup>

		<!-- 保险服务日期选择弹窗 -->
		<uni-popup ref="insuranceServicePopup" type="center" :mask-click="false">
			<view class="insurance-service-popup">
				<view class="popup-title">选择新的保险生效日期</view>
				<view class="popup-content">
					<text class="popup-tip">请选择新的保险生效日期，系统将更新保险信息</text>
					<uni-forms ref="insuranceServiceForm" :model="insuranceServiceForm" :rules="insuranceServiceRules">
						<uni-forms-item label="新保险生效日期" name="newEffectiveDate" required>
							<uni-datetime-picker
								v-model="insuranceServiceForm.newEffectiveDate"
								type="date"
								return-type="string"
								:start="todayDate"
								:end="getFutureDate"
								placeholder="请选择新的保险生效日期"
								:clear-icon="false">
							</uni-datetime-picker>
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="popup-actions">
					<button class="cancel-btn" @click="closeInsuranceServicePopup">取消</button>
					<button class="confirm-btn" @click="saveInsuranceService">确认</button>
				</view>
			</view>
		</uni-popup>

		<!-- 行驶证副本上传弹窗 -->
		<uni-popup ref="licenseBackPopup" type="center">
			<view class="upload-popup">
				<view class="popup-title">上传行驶证副本</view>
				<view class="popup-content">
					<text class="upload-tip">请上传该车辆的行驶证副本照片，系统将自动识别并更新车辆信息</text>
					<uni-file-picker 
						ref="licenseBackUpload"
						v-model="licenseBackFiles" 
						:image-styles="imageStyles"
						:sizeType="['compressed']" 
						return-type="object"
						@success="onLicenseBackUploadSuccess"
						@delete="onLicenseBackDelete"
						:disabled="isUploadingBack">
						行驶证副本
					</uni-file-picker>
					<view v-if="isUploadingBack" class="uploading-status">
						<uni-icons type="spinner-cycle" size="20" color="#007AFF"></uni-icons>
						<text class="uploading-text">正在识别行驶证副本，请稍候...</text>
					</view>
				</view>
				<view class="popup-actions">
					<button class="cancel-btn" @click="cancelLicenseBack" :disabled="isUploadingBack">
						{{ isUploadingBack ? '处理中...' : '取消' }}
					</button>
				</view>
			</view>
		</uni-popup>

		<!-- 提示弹窗 -->
		<uni-popup ref="messagePopup" type="message">
			<uni-popup-message :type="messageType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
import {
	store
} from '@/uni_modules/uni-id-pages/common/store'

	const db = uniCloud.databaseForJQL();
	
	export default {
		data() {
			return {
				formDataId: '',
				formData: {
				plate_number: '',
				license_info: {},
				insurance_info: {
					effective_date: ''
				},
				maintenance_info: {},
				inspection_info: {
					next_inspection_date: ''
				},
			license_photos: {},
			butler_bind_status: 0,
			butler_id: '',
			
			butler_bind_date: null,
			butler_expire_date: null,
			is_accident_vehicle: false,
			is_modified_vehicle: false
			},
				dateformat1: 'yyyy-MM-dd',
			todayDate: new Date().toISOString().split('T')[0],
			licenseBackFiles: [],
			isUploadingBack: false,
			messageType: 'success',
			messageText: '',
			imageStyles: {
				width: 400,
				height: 300
			},
				maintenanceForm: {
				lastDate: '',
				totalMileage: '',
				oilMileage: ''
				},
				maintenanceRules: {
					lastDate: [{
						required: true,
						message: '请选择上次保养日期',
						trigger: 'change'
					}],
					totalMileage: [{
						required: true,
						message: '请输入总公里数',
						trigger: 'blur'
					}],
					oilMileage: [{
						required: true,
						message: '请选择机油公里数',
						trigger: 'change'
					}]
				},
				insuranceServiceForm: {
					newEffectiveDate: ''
				},
				insuranceServiceRules: {
					newEffectiveDate: [{
						required: true,
						message: '请选择新的保险生效日期',
						trigger: 'change'
					}]
				},
				oilMileageOptions: [
					{ value: '8000', text: '8000km' },
					{ value: '6000', text: '6000km' }
				]
			}
		},
		computed: {
			// 是否有行驶证副本
			hasLicenseBack() {
				return !!this.formData.license_photos?.car_license_back?.url
			},

			// 保养信息是否未完善
			isMaintenanceIncomplete() {
				return !this.formData.maintenance_info?.last_maintenance_date || 
					   !this.formData.maintenance_info?.mileage
			},

			// 是否未绑定（绑定状态为0或绑定已超时）
			isUnbound() {
				// 绑定状态为0，直接未绑定
				if (this.formData.butler_bind_status === 0) {
					return true
				}
				
				// 检查绑定是否超时
				if (this.formData.butler_bind_status === 1 && this.formData.butler_expire_date) {
					const expireDate = new Date(this.formData.butler_expire_date)
					const today = new Date()
					return today > expireDate
				}
				
				return false
			},

			// 是否有待服务项目（处于可办期内）
			hasServicePending() {
				return this.isInsuranceServiceTime || this.isMaintenanceServiceTime || this.isInspectionServiceTime
			},
			
			// 一年前日期
			oneYearAgoDate() {
				const date = new Date()
				date.setFullYear(date.getFullYear() - 1)
				return date.toISOString().split('T')[0]
			},

			// 未来日期（用于车检日期选择的结束时间，设置为3年后）
			getFutureDate() {
				const date = new Date()
				date.setFullYear(date.getFullYear() + 3)
				return date.toISOString().split('T')[0]
			},

			// 信息是否完善
			isInfoComplete() {
				return this.formData.maintenance_info?.mileage > 0
			},

			// 是否已绑定车管家
			isBound() {
				return this.formData.butler_bind_status === 1
			},

			// 是否显示保养登记按钮
			showMaintenanceRegister() {
				return !this.formData.maintenance_info?.last_maintenance_date || 
					   !this.formData.maintenance_info?.mileage
			},

			// 保险是否到服务时间
			isInsuranceServiceTime() {
				if (!this.formData.insurance_info?.effective_date) {
					return false
				}
				
				const effectiveDate = new Date(this.formData.insurance_info.effective_date)
				const serviceDate = new Date(effectiveDate)
				serviceDate.setFullYear(serviceDate.getFullYear() + 1)
				serviceDate.setDate(serviceDate.getDate() - 28)
				
				return new Date() >= serviceDate
			},

			// 保养是否到服务时间
			isMaintenanceServiceTime() {
				if (!this.formData.maintenance_info?.last_maintenance_date) {
					return false
				}
				
				const lastDate = new Date(this.formData.maintenance_info.last_maintenance_date)
				const serviceDate = new Date(lastDate)
				serviceDate.setMonth(serviceDate.getMonth() + 6)
				
				return new Date() >= serviceDate
			},

			// 车检是否到服务时间
			isInspectionServiceTime() {
				if (!this.formData.inspection_info?.next_inspection_date) {
					return false
				}
				
				const nextDate = new Date(this.formData.inspection_info.next_inspection_date)
				const serviceDate = new Date(nextDate)
				serviceDate.setMonth(serviceDate.getMonth() - 1)
				
				return new Date() >= serviceDate
			},

			// 是否可以绑定更新（三期信息已完善）
			canBindUpdate() {
				return this.isInfoComplete && this.hasLicenseBack
			}
		},
		onLoad(e) {
			if (!e.id) {
				uni.showToast({
					icon: 'none',
					title: '请先选择车辆档案'
				});
				setTimeout(() => uni.navigateBack(), 500);
				return;
			}
			this.formDataId = e.id;
			this.getDetail(e.id);
		},
		onShareAppMessage() {
			return {
				title: '三期名片:' + this.formData.plate_number || '',
				path: '/pages/yycw-car-archives/card?id=' + this.formDataId
			}
		},
		methods: {
			// 获取详情数据
			async getDetail(id) {
				uni.showLoading({ mask: true });
				try {
					const res = await db.collection('yycw-car-archives').doc(id).get();
					if (res.data.length > 0) {
						this.formData = res.data[0];
						
						// 确保必需字段正确初始化
						if (!this.formData.insurance_info) {
							this.formData.insurance_info = { effective_date: '' }
						}
						if (!this.formData.maintenance_info) {
							this.formData.maintenance_info = {}
						}
						if (!this.formData.inspection_info) {
							this.formData.inspection_info = { next_inspection_date: '' }
						}
						if (!this.formData.license_photos) {
							this.formData.license_photos = {}
						}
						
						// 确保日期字段是字符串格式
						if (this.formData.insurance_info.effective_date && typeof this.formData.insurance_info.effective_date !== 'string') {
							this.formData.insurance_info.effective_date = this.formatDateString(this.formData.insurance_info.effective_date)
						}
						if (this.formData.inspection_info.next_inspection_date && typeof this.formData.inspection_info.next_inspection_date !== 'string') {
							this.formData.inspection_info.next_inspection_date = this.formatDateString(this.formData.inspection_info.next_inspection_date)
						}
						
					}
				} catch (err) {
					uni.showModal({
						content: err.message || '获取数据失败',
						showCancel: false
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 车主姓名加密
			maskOwnerName(name) {
				if (!name) return '--';
				if (name.length <= 1) return name;
				return name.charAt(0) + '*'.repeat(name.length - 1);
			},

			// 修改保险信息
			editInsurance() {
				// 手工录入：打开日期选择器
				this.$refs.insuranceDatePicker.show()
			},

			// 完成保险服务
			async completeInsuranceService() {
				// 计算默认的新保险生效日期（当前保险生效日期+1年）
				const currentDate = new Date(this.formData.insurance_info.effective_date)
				const defaultNewDate = new Date(currentDate)
				defaultNewDate.setFullYear(defaultNewDate.getFullYear() + 1)
				
				this.insuranceServiceForm.newEffectiveDate = this.formatDateString(defaultNewDate)
				this.$refs.insuranceServicePopup.open()
			},

			// 登记保养信息
			registerMaintenance() {
				// 使用页面上已有的保养信息作为缺省值
				const existingLastDate = this.formData.maintenance_info?.last_maintenance_date
				const existingMileage = this.formData.maintenance_info?.mileage
				const existingOilMileage = this.formData.maintenance_info?.oil_mileage
				
				this.maintenanceForm = {
					lastDate: existingLastDate ? this.formatDateString(existingLastDate) : '',
					totalMileage: existingMileage ? existingMileage.toString() : '',
					oilMileage: existingOilMileage ? existingOilMileage.toString() : ''
				}
				this.$refs.maintenancePopup.open()
			},

			// 关闭保养弹窗
			closeMaintenancePopup() {
				this.$refs.maintenancePopup.close()
			},

			// 保存保养信息
			async saveMaintenanceInfo() {
				// 表单验证
				if (!this.maintenanceForm.lastDate) {
					this.showMessage('error', '请选择保养日期')
					return
				}
				if (!this.maintenanceForm.totalMileage) {
					this.showMessage('error', '请输入总公里数')
					return
				}
				if (!this.maintenanceForm.oilMileage) {
					this.showMessage('error', '请选择机油公里数')
					return
				}

				// 只更新本地数据
				this.formData.maintenance_info.last_maintenance_date = this.maintenanceForm.lastDate
				this.formData.maintenance_info.mileage = parseInt(this.maintenanceForm.totalMileage)
				this.formData.maintenance_info.oil_mileage = parseInt(this.maintenanceForm.oilMileage)

				this.$refs.maintenancePopup.close()
				this.showMessage('success', '保养信息已保存')
			},

			// 完成保养服务
			async completeMaintenanceService() {
				uni.showModal({
					title: '确认保养服务',
					content: '确认已完成保养服务，系统将自动更新保养信息',
					success: async (res) => {
						if (res.confirm) {
							await this.processMaintenanceService()
						}
					}
				})
			},

			// 处理保养服务
			async processMaintenanceService() {
				try {
					uni.showLoading({ title: '处理中...' })
					
					const today = new Date()
					const nextDate = new Date(today)
					nextDate.setMonth(nextDate.getMonth() + 6)

					await db.collection('yycw-car-archives').doc(this.formDataId).update({
						maintenance_info: {
							last_maintenance_date: today,
							next_maintenance_date: nextDate,
							mileage: 0,
							oil_mileage: 0
						},
						butler_bind_status: 2
					})

					this.formData.maintenance_info.last_maintenance_date = today
					this.formData.maintenance_info.next_maintenance_date = nextDate
					this.formData.maintenance_info.mileage = 0
					this.formData.maintenance_info.oil_mileage = 0
					this.formData.butler_bind_status = 2

					this.showMessage('success', '保养服务已完成')

				} catch (error) {
					console.error('处理失败:', error)
					this.showMessage('error', '处理失败，请重试')
				} finally {
					uni.hideLoading()
				}
			},

			// 车检相关方法
			editInspection() {
				// 手工录入：打开日期选择器
				this.$refs.inspectionDatePicker.show()
			},

			async completeInspectionService() {
					uni.showModal({
					title: '确认车检服务',
					content: '确认已完成车检服务，系统将自动计算下次车检日期',
					success: async (res) => {
						if (res.confirm) {
							await this.processInspectionService()
						}
					}
				})
			},

			async processInspectionService() {
				try {
					uni.showLoading({ title: '处理中...' })
					
					const today = new Date()
					const nextYear = new Date(today)
					nextYear.setFullYear(nextYear.getFullYear() + 1)

					await db.collection('yycw-car-archives').doc(this.formDataId).update({
						inspection_info: {
							last_inspection_date: today,
							next_inspection_date: nextYear
						},
						butler_bind_status: 2
					})

					this.formData.inspection_info.last_inspection_date = today
					this.formData.inspection_info.next_inspection_date = nextYear
					this.formData.butler_bind_status = 2

					this.showMessage('success', '车检服务已完成')

				} catch (error) {
					console.error('处理失败:', error)
					this.showMessage('error', '处理失败，请重试')
				} finally {
					uni.hideLoading()
				}
			},

			// 操作按钮方法
			async bindUpdate() {
				try {
					uni.showLoading({ title: '绑定中...' })
					
					const currentUserId = store.userInfo._id
					
					// 直接更新数据库，绑定日期和到期日期由数据库扩展自动处理
					await db.collection('yycw-car-archives').doc(this.formDataId).update({
						butler_id: currentUserId,
						butler_bind_status: 1,
						insurance_info: this.formData.insurance_info,
						maintenance_info: this.formData.maintenance_info,
						inspection_info: this.formData.inspection_info
					})

					// 直接更新本地数据，避免重新获取数据
					this.formData.butler_id = currentUserId
					this.formData.butler_bind_status = 1
					
					this.showMessage('success', '绑定更新成功')
				// 返回work页面，携带plateNumber参数
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/yycw-car-archives/work?plateNumber=' + this.formData.plate_number
					})
				}, 500)
				} catch (error) {
					console.error('绑定失败:', error)
					this.showMessage('error', '绑定失败，请重试')
				} finally {
					uni.hideLoading()
				}
			},

			// 上传行驶证副本
			uploadLicenseBack() {
				this.licenseBackFiles = []
				this.isUploadingBack = false
				this.$refs.licenseBackPopup.open()
			},

			// 行驶证副本上传成功
			async onLicenseBackUploadSuccess(event) {
				this.isUploadingBack = true
				console.log('行驶证副本上传成功:', event)
				
				try {
					const uploadedFile = event.tempFiles[0]
					const params = {
						url: uploadedFile.url,
						type: 'back',
						archivesId: this.formDataId,
						extname: uploadedFile.extname,
						name: uploadedFile.name
					}
					
					// 调用云函数进行识别
					const result = await uniCloud.callFunction({
						name: 'yycw-car-archives',
						data: {
							action: 'recognizeVehicleLicenseToComplete',
							params: params
						}
					})
					console.log('行驶证副本识别结果:', JSON.stringify(result))
					if (result.result.errCode === 0) {
						// 识别成功，直接更新本地数据
						if (!this.formData.license_photos) {
							this.formData.license_photos = {}
						}
						this.formData.license_photos.car_license_back = {
							url: uploadedFile.url,
							name: uploadedFile.name,
							extname: uploadedFile.extname
						}
						
						// 如果云函数返回了更新的车辆信息，同步更新到本地
						if (result.result.data) {
							// 更新识别到的车辆信息
							if (result.result.data.license_info) {
								this.formData.license_info = {
									...this.formData.license_info,
									...result.result.data.license_info
								}
							}
							// 更新其他可能的信息
							if (result.result.data.insurance_info) {
								this.formData.insurance_info = {
									...this.formData.insurance_info,
									...result.result.data.insurance_info
								}
							}
							if (result.result.data.inspection_info) {
								this.formData.inspection_info = {
									...this.formData.inspection_info,
									...result.result.data.inspection_info
								}
							}
						}
						
						// 关闭上传弹窗并清空文件列表
						this.$refs.licenseBackPopup.close()
						this.licenseBackFiles = []
						
						// 显示成功消息
						this.showMessage('success', '行驶证副本识别成功，信息已更新')
					} else {
						uni.showModal({
							content: result.result.errMsg || '识别失败',
							showCancel: false
						})
						this.showMessage('error', result.result.errMsg || '识别失败，请重新上传')
						this.licenseBackFiles = []
					}
				} catch (error) {
					console.error('行驶证副本识别失败:', error)
					this.showMessage('error', '识别失败，请重新上传')
					this.licenseBackFiles = []
				} finally {
					this.isUploadingBack = false
				}
			},

			// 行驶证副本删除
			onLicenseBackDelete(event) {
				console.log('删除行驶证副本:', event)
			},

			// 取消上传行驶证副本
			cancelLicenseBack() {
				if (this.isUploadingBack) {
					this.showMessage('warning', '正在处理中，请稍候')
					return
				}
				this.$refs.licenseBackPopup.close()
				this.licenseBackFiles = []
				this.isUploadingBack = false
			},
			// 预览图片
			previewImage(url) {
				if (!url) return;
				uni.previewImage({
					urls: [url],
					current: url
				});
			},

			// 显示消息
			showMessage(type, text) {
				this.messageType = type
				this.messageText = text
				this.$refs.messagePopup.open()
			},

			// 获取保险状态类型（用于图标颜色）
			getInsuranceStatusType() {
				if (!this.formData.insurance_info?.effective_date) {
					return 'error'
				}
				if (this.isInsuranceServiceTime) {
					return 'warning'
				}
				return 'success'
			},

			// 获取保养状态类型（用于图标颜色）
			getMaintenanceStatusType() {
				if (this.isMaintenanceIncomplete) {
					return 'error'
				}
				if (this.isMaintenanceServiceTime) {
					return 'warning'
				}
				return 'success'
			},

			// 获取车检状态类型（用于图标颜色）
			getInspectionStatusType() {
				if (!this.formData.inspection_info?.next_inspection_date) {
					return 'error'
				}
				if (this.isInspectionServiceTime) {
					return 'warning'
				}
				return 'success'
			},

			// 格式化日期
			formatDate(date) {
				if (!date) return '--'
				return new Date(date).toLocaleDateString('zh-CN')
			},

			// 格式化日期为 yyyy-MM-dd 字符串
			formatDateString(date) {
				if (!date) return ''
				const d = new Date(date)
				const year = d.getFullYear()
				const month = String(d.getMonth() + 1).padStart(2, '0')
				const day = String(d.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},

			// 获取保险可办期范围
			getInsuranceTodoRange() {
				if (!this.formData.insurance_info?.effective_date) return '--'
				
				const effectiveDate = new Date(this.formData.insurance_info.effective_date)
				const startDate = new Date(effectiveDate)
				startDate.setFullYear(startDate.getFullYear() + 1)
				startDate.setDate(startDate.getDate() - 28)
				
				const endDate = new Date(effectiveDate)
				endDate.setFullYear(endDate.getFullYear() + 1)
				
				return `${this.formatDateString(startDate)} 至 ${this.formatDateString(endDate)}`
			},

			// 获取保养可办期范围
			getMaintenanceTodoRange() {
				if (!this.formData.maintenance_info?.last_maintenance_date) return '--'
				
				const lastDate = new Date(this.formData.maintenance_info.last_maintenance_date)
				const startDate = new Date(lastDate)
				startDate.setMonth(startDate.getMonth() + 6)
				
				const endDate = new Date(lastDate)
				endDate.setMonth(endDate.getMonth() + 8)
				
				return `${this.formatDateString(startDate)} 至 ${this.formatDateString(endDate)}`
			},

			// 获取车检可办期范围
			getInspectionTodoRange() {
				if (!this.formData.inspection_info?.next_inspection_date) return '--'
				
				const nextDate = new Date(this.formData.inspection_info.next_inspection_date)
				const startDate = new Date(nextDate)
				startDate.setMonth(startDate.getMonth() - 1)
				
				return `${this.formatDateString(startDate)} 至 ${this.formatDateString(nextDate)}`
			},

			// 获取状态颜色
			getStatusColor(type) {
				const colorMap = {
					'error': '#ff9900',      // 橙色 - 初始化信息待完善
					'warning': '#ff4757',    // 红色 - 可办期（待服务）
					'success': '#19be6b'     // 绿色 - 已完成
				}
				return colorMap[type] || '#909399'
			},

			// 切换事故车标记
			async toggleAccidentVehicle() {
				if (!this.hasLicenseBack) {
					this.showMessage('warning', '请先补充行驶证副本')
					return
				}
				
				const newStatus = !this.formData.is_accident_vehicle
				const actionText = newStatus ? '标记为事故车' : '取消事故车标记'
				
				uni.showModal({
					title: '确认操作',
					content: `确认${actionText}？这将影响车检频率计算。`,
					success: async (res) => {
						if (res.confirm) {
							await this.updateVehicleMarks({
								is_accident_vehicle: newStatus,
								is_modified_vehicle: this.formData.is_modified_vehicle
							})
						}
					}
				})
			},

			// 切换改装车标记
			async toggleModifiedVehicle() {
				if (!this.hasLicenseBack) {
					this.showMessage('warning', '请先补充行驶证副本')
					return
				}
				
				const newStatus = !this.formData.is_modified_vehicle
				const actionText = newStatus ? '标记为改装车' : '取消改装车标记'
				
				uni.showModal({
					title: '确认操作',
					content: `确认${actionText}？这将影响车检频率计算。`,
					success: async (res) => {
						if (res.confirm) {
							await this.updateVehicleMarks({
								is_accident_vehicle: this.formData.is_accident_vehicle,
								is_modified_vehicle: newStatus
							})
						}
					}
				})
			},

			// 更新车辆标记
			async updateVehicleMarks(marks) {
				try {
					uni.showLoading({ title: '更新中...', mask: true })
					
					const result = await uniCloud.callFunction({
						name: 'yycw-car-archives',
						data: {
							action: 'updateVehicleMarks',
							params: {
								card_id: this.formDataId,
								...marks
							}
						}
					})

					if (result.result.errCode === 0) {
						// 更新本地数据
						this.formData.is_accident_vehicle = marks.is_accident_vehicle
						this.formData.is_modified_vehicle = marks.is_modified_vehicle
						
						// 重新获取数据以更新检验日期
						await this.getDetail(this.formDataId)
						
						this.showMessage('success', '车辆标记更新成功，检验日期已重新计算')
					} else {
						this.showMessage('error', result.result.errMsg || '更新失败')
					}

				} catch (error) {
					console.error('更新车辆标记失败:', error)
					this.showMessage('error', '更新失败，请重试')
				} finally {
					uni.hideLoading()
				}
			},

			// 关闭保险服务弹窗
			closeInsuranceServicePopup() {
				this.$refs.insuranceServicePopup.close()
			},

			// 保存保险服务信息
			async saveInsuranceService() {
				// 表单验证
				if (!this.insuranceServiceForm.newEffectiveDate) {
					this.showMessage('error', '请选择新的保险生效日期')
					return
				}

				try {
					uni.showLoading({ title: '处理中...', mask: true })
					
					const newDate = new Date(this.insuranceServiceForm.newEffectiveDate)

					// 单独更新数据库保险生效日期
					await db.collection('yycw-car-archives').doc(this.formDataId).update({
						insurance_info: {
							effective_date: newDate
						}
					})

					// 更新本地数据
					this.formData.insurance_info.effective_date = this.insuranceServiceForm.newEffectiveDate

					this.$refs.insuranceServicePopup.close()
					this.showMessage('success', '保险服务已完成')

				} catch (error) {
					console.error('处理失败:', error)
					this.showMessage('error', '处理失败，请重试')
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	// uni-section 组件自定义样式
	::v-deep .uni-section {
		margin-bottom: 24rpx;
	}
	
	::v-deep .uni-section__head {
		padding: 20rpx 0 16rpx 0;
	}
	
	::v-deep .uni-section__head-tag {
		margin-right: 12rpx;
	}
	
	::v-deep .uni-section__head-content {
		flex: 1;
	}
	
	::v-deep .uni-section__head-content-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #303133;
	}
	
	::v-deep .uni-section__head-content-sub {
		font-size: 26rpx;
		color: #909399;
		margin-top: 4rpx;
	}

	.header-button-group {
		display: flex;
		gap: 8rpx;
		
		.header-btn {
			border: none;
			border-radius: 4rpx;
			padding: 8rpx 16rpx;
			font-size: 22rpx;
			
			&.primary {
				background: #007AFF;
				color: white;
			}
			
			&.secondary {
				background: #f5f5f5;
				color: #666;
			}

			&.urgent {
				background: #ff4757;
				color: white;
			}
		}
	}

	.tag-group {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 8rpx;
		justify-content: flex-end;
	}

	.missing-license-notice {
		background: #fff2e8;
		border: 1rpx solid #ff6b35;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.notice-content {
			display: flex;
			align-items: center;
			gap: 12rpx;
		}

		.notice-text {
			color: #ff6b35;
			font-size: 28rpx;
		}

		.upload-license-btn {
			background: #ff6b35;
			color: white;
			border: none;
			border-radius: 8rpx;
			padding: 12rpx 24rpx;
			font-size: 26rpx;
		}
	}

	.completion-status {
		margin-bottom: 20rpx;
	}

	.operation-section {
		margin-top: 40rpx;

		.operation-buttons {
			display: flex;
			gap: 16rpx;
			padding: 24rpx;
			background: white;
			border-radius: 16rpx;
			margin-top: -16rpx; // 减少uni-section的底部间距
		}

		.operation-btn {
			flex: 1;
			border: none;
			border-radius: 8rpx;
			padding: 20rpx 12rpx;
			font-size: 24rpx;
			text-align: center;
			color: white;

			// 单个按钮样式
			&.single-btn {
				flex: none;
				width: 100%;
				max-width: 300rpx;
				margin: 0 auto;
			}

			// 绑定更新按钮 - 红色
			&.bind-update-btn {
				background: #ff4757;
				
				&.disabled {
					background: #ffb3ba;
					color: #999;
				}
			}

			// 任务派单按钮 - 黄色
			&.task-btn {
				background: #ffa502;
				
				&.disabled {
					background: #ffd700;
					color: #999;
				}
			}

			// 分享名片和保存按钮 - 绿色
			&.share-btn, &.save-btn {
				background: #2ed573;
				
				&.disabled {
					background: #a4d7b8;
					color: #999;
					opacity: 0.6;
				}
			}
		}
	}

	.maintenance-popup {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx;
		width: 600rpx;
	}

	.insurance-service-popup {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx;
		width: 600rpx;
	}

	.upload-popup {
		background: white;
		border-radius: 20rpx;
		padding: 40rpx;
		width: 600rpx;
		text-align: center;
	}

	.popup-title {
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 30rpx;
	}

	.popup-actions {
		display: flex;
		gap: 20rpx;
		margin-top: 40rpx;
	}

	.cancel-btn, .confirm-btn {
		flex: 1;
		padding: 24rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
		border: none;
	}

	.cancel-btn {
		background: #f5f5f5;
		color: #666;
		
		&:disabled {
			// 使用uniapp基础组件自带的禁用样式
		}
	}

	.confirm-btn {
		background: #007AFF;
		color: white;

		&:disabled {
			// 使用uniapp基础组件自带的禁用样式
		}
	}

	.popup-content {
		padding: 20rpx 0;
		text-align: center;

		.upload-tip {
			color: #666;
			font-size: 26rpx;
			line-height: 1.6;
			margin-bottom: 30rpx;
			display: block;
			text-align: center;
		}

		.popup-tip {
			color: #666;
			font-size: 26rpx;
			line-height: 1.6;
			margin-bottom: 30rpx;
			display: block;
			text-align: center;
		}
	}

	.uploading-status {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		margin-top: 20rpx;
		padding: 16rpx;
		background: #f8f9fa;
		border-radius: 8rpx;

		.uploading-text {
			color: #007AFF;
			font-size: 26rpx;
		}
	}

	.upload-area {
		border: 2rpx dashed #ddd;
		border-radius: 10rpx;
		padding: 40rpx;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.license-preview {
		width: 100%;
		height: 300rpx;
		object-fit: contain;
	}

	.upload-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;

		.upload-text {
			color: #999;
			font-size: 26rpx;
		}
	}

	.info-card, .photo-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f4f4f5;
		
		&:last-child {
			border-bottom: none;
		}
		
		.label {
			font-size: 28rpx;
			color: #606266;
			flex-shrink: 0;
			width: 160rpx;
		}
		
		.value {
			font-size: 28rpx;
			color: #303133;
			text-align: right;
			flex: 1;
			margin-left: 8rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			min-width: 0;
		}
		
		// 日期选择器样式
		:deep(.uni-datetime-picker) {
			flex: 1;
			min-width: 0;
			
			.uni-datetime-picker__input-text {
				font-size: 28rpx;
				color: #303133;
				text-align: right;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			
			.uni-datetime-picker__input-placeholder {
				font-size: 28rpx;
				color: #c0c4cc;
				text-align: right;
			}
		}
		
		// 输入框样式
		:deep(.uni-easyinput) {
			flex: 1;
			min-width: 0;
			
			.uni-easyinput__content {
				text-align: right;
			}
			
			.uni-easyinput__content-input {
				font-size: 28rpx;
				color: #303133;
				text-align: right;
			}
			
			.uni-easyinput__content-placeholder {
				font-size: 28rpx;
				color: #c0c4cc;
				text-align: right;
			}
		}
		
		// 选择框样式
		:deep(.uni-data-checkbox) {
			flex: 1;
			min-width: 0;
			
			.uni-data-checkbox__item {
				font-size: 24rpx;
				padding: 8rpx 16rpx;
				margin: 0 8rpx 0 0;
			}
		}
	}

	.info-item-with-button {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f4f4f5;
		
		.info-content {
			display: flex;
			align-items: center;
			flex: 1;
			
			.label {
				font-size: 28rpx;
				color: #606266;
				margin-right: 20rpx;
			}
		}
		
		.button-area {
			flex-shrink: 0;
		}
		
		.button-group {
			display: flex;
			gap: 12rpx;
		}
	}

	.photo-item {
		text-align: center;
		
		.photo-image {
			width: 100%;
			height: 200rpx;
			border-radius: 12rpx;
			border: 1rpx solid #ebeef5;
		}
		
		.photo-placeholder {
			width: 100%;
			height: 200rpx;
			border: 2rpx dashed #dcdfe6;
			border-radius: 12rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			background-color: #fafafa;
		}
		
		.placeholder-text {
			font-size: 24rpx;
			color: #909399;
			margin-top: 12rpx;
		}
		
		.photo-label {
			display: block;
			margin-top: 16rpx;
			font-size: 26rpx;
			color: #606266;
		}
	}

	.maintenance-popup {
		width: 680rpx;
		padding: 30rpx 20rpx;
		background-color: #fff;
		border-radius: 16rpx;
		
		.maintenance-popup-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #303133;
			text-align: center;
			margin-bottom: 30rpx;
		}
		
		.maintenance-popup-buttons {
			display: flex;
			justify-content: space-between;
			gap: 20rpx;
			margin-top: 30rpx;
			padding: 0 10rpx;
			
			.maintenance-button {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				border-radius: 8rpx;
				font-size: 28rpx;
				
				&.cancel {
					background-color: #f5f5f5;
					color: #606266;
				}
				
				&.confirm {
					background-color: #409eff;
					color: #fff;
				}
			}
		}
	}

	// 车辆标记样式
	.mark-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16rpx 0;
		border-bottom: 1rpx solid #f4f4f5;

		&:last-child {
			border-bottom: none;
		}

		.mark-label {
			font-size: 26rpx;
			color: #606266;
			margin-right: 12rpx;
		}

		.mark-edit-btn {
			background: #f8f9fa;
			color: #666;
			border: 1rpx solid #e4e7ed;
			border-radius: 6rpx;
			padding: 8rpx 16rpx;
			font-size: 22rpx;
			margin-left: 12rpx;

			&:disabled {
				// 使用uniapp基础组件自带的禁用样式
			}
		}
	}

	// 重点色显示样式 - 可办期到达时使用
	.urgent-section {
		::v-deep .uni-section__head-content-title {
			color: #ff4757 !important;
			font-weight: 700;
		}
	}

	.urgent-card {
		background-color: #fff1f0 !important;
		border: 2rpx solid #ff4757 !important;
		box-shadow: 0 4rpx 16rpx rgba(255, 71, 87, 0.15) !important;
	}
</style>